package com.ruoyi.admin.service.impl;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.admin.mapper.UserModuleMapper;
import com.ruoyi.admin.domain.UserModule;
import com.ruoyi.admin.service.UserAnswerService;
import com.ruoyi.admin.service.UserModuleService;
import com.ruoyi.api.model.request.AnswerReq;
import com.ruoyi.api.model.request.ModuleSubmitReq;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * (UserModule)表服务实现类
 *
 * @author zhoujun
 * @since 2023-04-11 14:19:11
 */
@Service("userModuleService")
public class UserModuleServiceImpl extends ServiceImpl<UserModuleMapper, UserModule> implements UserModuleService {

    @Autowired
    private UserAnswerService userAnswerService;

    @Override
    public boolean submitModule(ModuleSubmitReq moduleSubmitReq){
        UserModule userModule = new UserModule();
        userModule.setStudentId(SecurityUtils.getUserId());
        userModule.setPaperId(moduleSubmitReq.getPaperId());
        userModule.setModuleType(moduleSubmitReq.getModuleType());
        userModule.setModuleName(moduleSubmitReq.getModuleName());
        userModule.setCorrectFlag(0);
        userModule.setExamType(moduleSubmitReq.getExamType());
        userModule.setCreateBy(SecurityUtils.getUsername());
        userModule.setCreateTime(new Date());
        userModule.setDelFlag(0);
        userModule.setUserPaperId(moduleSubmitReq.getUserPaperId());

        List<AnswerReq> answerReqList = moduleSubmitReq.getTopicList().stream().map(ModuleSubmitReq.TopicReq::getAnswerList)
                .flatMap(Collection::stream)
                .map(m->{
                    m.setUserPaperId(moduleSubmitReq.getUserPaperId());
                    m.setPaperId(moduleSubmitReq.getPaperId());
                    return m;
                })
                .collect(Collectors.toList());
        int score = userAnswerService.paperAnswer(answerReqList);
        userModule.setModuleScore(score);
        return this.save(userModule);
    }
}

